package com.learn.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.junit.Test;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.KeyPair;

public class Demo {

    @Test
    public void test() throws Exception {
        String value = "hello";
        // JDK支持 HmacMD5、HmacSHA1、HmacSHA224、HmacSHA256、HmacSHA384和HmacSHA512六种算法
        String algorithm = "HmacSHA256";
        // 初始化KeyGenerator
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
        // 构建秘钥
        SecretKey secretKey = keyGenerator.generateKey();
        // 获得秘钥
        byte[] key = secretKey.getEncoded();
        // 还原秘钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, algorithm);
        // 打印下秘钥
        System.out.println(Base64.encodeBase64String(secretKeySpec.getEncoded()));
        // 实例化Mac
        Mac mac = Mac.getInstance(algorithm);
        // 初始化Mac
        mac.init(secretKeySpec);
        // 获取消息摘要
        byte[] bytes = mac.doFinal(value.getBytes());
        // 转换为16进制
        System.out.println(Hex.encodeHexString(bytes));
    }


    @Test
    public void test2(){
        String text = "我是一段测试aaaa";

        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        byte[] privateKey = pair.getPrivate().getEncoded();
        byte[] publicKey = pair.getPublic().getEncoded();

        SM2 sm2 = SmUtil.sm2(privateKey, publicKey);
        // 公钥加密，私钥解密
        String encryptStr = sm2.encryptBcd(text, KeyType.PublicKey);
        String decryptStr = StrUtil.utf8Str(sm2.decryptFromBcd(encryptStr, KeyType.PrivateKey));

        System.out.println(decryptStr);
    }
}
